/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Controllers;

import com.dpy.appmvdpy.Facades.ClientesFacade;
import com.dpy.appmvdpy.Facades.DefaultFacade;
import com.dpy.appmvdpy.Facades.VendedorFacade;
import com.dpy.appmvdpy.Helpers.StaticSources;
import com.dpy.appmvdpy.Models.Clientes;
import com.dpy.appmvdpy.Models.Exporters.ClientExporter;
import com.dpy.appmvdpy.Models.Exporters.Exporter;
import com.dpy.appmvdpy.Models.Importers.ClientImporter;
import com.dpy.appmvdpy.Models.Importers.Importer;
import com.dpy.appmvdpy.Models.Users;
import com.dpy.appmvdpy.Models.Validators.ClientesValidator;
import com.dpy.appmvdpy.Models.Validators.DefaultValidator;
import com.dpy.appmvdpy.Models.Vendedor;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Scope;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author ac_psoares
 */
@Controller
@RequestMapping("/clientes")
@PreAuthorize("hasRole('ROLE_USER')")
public class ClientesController extends DefaultController<Clientes> {

    @Autowired
    public ClientesFacade facade;
    
    @Autowired
    public ClientesValidator validator;
    
    @Autowired
    public VendedorFacade vendedorFacade;
    
    @Autowired
    public ClientImporter importer;
    
    @Autowired
    public ClientExporter exporter;
       
    
    public ClientesController()
    {
        super(Clientes.class,"clientes");
    }
    
    @InitBinder
    protected void initBinder(WebDataBinder binder) throws Exception {
        binder.registerCustomEditor(Vendedor.class, "vendedor", new PropertyEditorSupport() {

            @Override
            public String getAsText() {
                return getValue() == null ? "" : ((Vendedor) getValue()).getId().toString();
            }

            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                Vendedor user = vendedorFacade.getById(Integer.valueOf(text));
                setValue(user);
            }
        });
        
         binder.registerCustomEditor(Date.class, "dataCadastro", new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), false));
    }
         
    @Override
    public DefaultFacade<Clientes> getFacade() {
        return this.facade;
    }

    @Override
    public Clientes createObject() {
        return new Clientes();
    }

    @Override
    public DefaultValidator<Clientes> getValidator() {
        return this.validator;
    }
    
    @Override
    @PreAuthorize("hasRole('ROLE_USER')")
    public ModelAndView create() {
        ModelAndView model = super.create();
        Clientes cliente = (Clientes)model.getModel().get("model");
        cliente.setDataCadastro(Calendar.getInstance().getTime());
        
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        for(GrantedAuthority g: user.getAuthorities())
        {
            if("ROLE_USER".equals(g.getAuthority()))
            {
                cliente.setCodigo(String.valueOf(vendedorFacade.proxNumFaixa(vendedorFacade.getVendedorByUser(user.getUsername())) + 1));
                cliente.setVendedor(vendedorFacade.getVendedorByUser(user.getUsername()));
            }
            break;
            
        }
        model.addObject("estados",StaticSources.estados());
        model.addObject("vendedorList",vendedorFacade.listAll());
        return model;
    }

    @Override
    @PreAuthorize("hasRole('ROLE_USER')")
    public ModelAndView edit(int id) {
        ModelAndView model = super.edit(id);
        Clientes cli = (Clientes) model.getModel().get("model");
        cli.setIntegrado(Boolean.FALSE);
        model.addObject("vendedorList",vendedorFacade.listAll());
        model.addObject("estados",StaticSources.estados());
        return model;
    }

    @Override
    @PreAuthorize("hasRole('ROLE_USER')")
    public ModelAndView delete(int id) {
        return super.delete(id);
    }

    @Override
    @PreAuthorize("hasRole('ROLE_USER')")
    public ModelAndView detail(int id) {
        return super.detail(id);
    }

    @Override
    @PreAuthorize("hasRole('ROLE_USER')")
    public ModelAndView list(@RequestParam(required=true,defaultValue="0")int pag) {
         User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        for(GrantedAuthority g: user.getAuthorities())
        {
            if("ROLE_USER".equals(g.getAuthority()))
            {               
                Vendedor v = vendedorFacade.getVendedorByUser(user.getUsername());
                ModelAndView model = new ModelAndView("/" + controllerName + "/list");
                List<Clientes> list = facade.listByVendedorId(v.getId(),pag);
                model.addObject("listModel",list);
                model.addObject("pageNumbers",facade.pageNumbers(v.getId()));
                return model;
            }
            break;            
        }
        return super.list(pag);
    }

    @Override
    @PreAuthorize("hasRole('ROLE_USER')")
    public ModelAndView search(String name) {
        return super.search(name);
    }
       

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return super.download(request, response);
    }

    @Override
    public Exporter<Clientes> getExporter() {        
       // File f = new File("cliente-" + (new Date()).toString().replace(":", "-") + ".txt");
        File f = new File("CLIENTE.TXT");
        exporter.setFile(f);
        return exporter;
    }

    @Override
    public Importer<Clientes> getImporter(File file) {
        importer.setFile(file);
        return importer;
    }  
}
